package com.zdy.im.tio.command.handler;



import com.sixeco.framework.common.api.ApiDoc;
import com.sixeco.framework.common.enums.SysResultCodeEnum;
import com.sixeco.framework.http.exception.SystemRuntimeException;
import com.zdy.im.common.exception.ImException;
import com.zdy.im.core.ICommand;
import com.zdy.im.tio.command.AbstractCommandHandler;
import com.zdy.im.tio.command.Command;
import com.zdy.im.tio.packets.HandshakeRequestVo;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.stereotype.Component;
import org.tio.core.ChannelContext;
import org.tio.core.intf.Packet;
import org.tio.http.common.HttpRequest;

import javax.annotation.Resource;

/**
 * 版本: [1.0]
 * 功能说明: 握手cmd命令处理器
 * @Author 作者 : zdy
 * @CreateDate 创建时间: 2021-02-30
 */
@Component
@ApiDoc(module = "WebSocket 项目文档",group = "SOCKET-GROUP")
public class HandshakeRequestHandler extends AbstractCommandHandler {

	@Resource
	private DefaultTokenServices defaultTokenServices;

	@Override
	public ICommand command() {
		return Command.COMMAND_HANDSHAKE_REQ;
	}

	@ApiDoc(
			cmd = "1",methodType = "ws",
			value = "握手协议协议 cmd=1",
			request = HandshakeRequestVo.class,
			response = boolean.class
	)
	@Override
	public Packet handler(Packet packet, ChannelContext channelContext) throws ImException {

//		HandshakeCmdProcessor handshakeProcessor = this.getMultiProcessor(channelContext,HandshakeCmdProcessor.class);
//		if(Objects.isNull(handshakeProcessor)){
//			JimServerAPI.remove(channelContext, "没有对应的握手协议处理器HandshakeCmdProcessor...");
//			return null;
//		}
//		ImPacket handShakePacket = handshakeProcessor.handshake(packet, channelContext);
//		if (handShakePacket == null) {
//			JimServerAPI.remove(channelContext, "业务层不同意握手");
//			return null;
//		}
//		JimServerAPI.send(channelContext, handShakePacket);
		//		handshakeProcessor.onAfterHandshake(request, channelContext);

		HttpRequest httpRequest = (HttpRequest)packet;
		//Map<String,Object[]> map = httpRequest.getParams();
		String token = httpRequest.getParam("token");
		//todo 先注释用户账号验证
		if(null == token){
			throw new SystemRuntimeException(SysResultCodeEnum.SYS_TOKEN_NULL);
		}
//		OAuth2Authentication auth2Authentication = defaultTokenServices.loadAuthentication(token);
//		User user = (User) auth2Authentication.getUserAuthentication().getPrincipal();
//		if(null == user){
//			throw new SystemRuntimeException(SysResultCodeEnum.SYS_USER_CODE_NOT);
//		}
//		HttpRequest handshake = this.getHandshakeRequest(channelContext);
//		if(handshake == null){
////			Tio.remove(channelContext, "业务层不同意握手");
////			return null;
//		}
//		Tio.send(channelContext, httpRequest);
		return null;
	}


}
